#include <opencv2/legacy/compat.hpp>

#include "HoughLines.h"
#include "../utils/Logger.h"

HoughLines::HoughLines(int threshold, int minLength, int separation, Effects *effects) :
        threshold(threshold),
        minLength(minLength),
        separation(separation),
        effects(effects)
{
}

HoughLines::~HoughLines() {
    if (effects)
        delete effects;
}

IplImage* HoughLines::apply(const IplImage* in) {
    Log << "Applying hough lines effect." << endl;

    IplImage *tmp = (IplImage*) in;
    if (NULL != effects && effects->any()) {
        tmp = effects->apply(in);
    }
    if (1 != tmp->nChannels) {
        IplImage *tmp2 = grayEffect.apply(tmp);
        if (in != tmp)
            cvReleaseImage(&tmp);
        tmp = tmp2;
    }

    CvMemStorage *storage = cvCreateMemStorage();
    CvSeq *lines = cvHoughLines2(tmp, storage, CV_HOUGH_PROBABILISTIC, 1, CV_PI / 180,
            threshold, minLength, separation);

    cvReleaseImage(&tmp);

    IplImage *out = cvCreateImage(cvSize(in->width, in->height), in->depth, in->nChannels);
    cvCopy(in, out);
    for (int i = 0; i < lines->total; i++) {
        CvPoint* line = (CvPoint*) cvGetSeqElem(lines, i);
        cvLine(out, line[0], line[1], CV_RGB(0, 0, 255));
    }

    cvReleaseMemStorage(&storage);

    return out;
}
